package fun.coding.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSumII {

	public static void main(String[] args) {
		int[] num = {10, 1, 2, 7, 6, 1, 5};
		CombinationSumII cs2 = new CombinationSumII();
		List<List<Integer>> r = cs2.combinationSum2(num, 8);
		
		for (List<Integer> l : r) {
			for (int i : l) {
				System.out.print(i + ",");
			}
			System.out.println();
		}
	}
	
	public List<List<Integer>> combinationSum2(int[] num, int target) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		List<Integer> sol = new ArrayList<Integer>();
		Arrays.sort(num);
		
		helper(num, 0, target, res, sol);
		return res;
	}
	
	public void helper(int[] num, int start, int target, List<List<Integer>> res, List<Integer> sol) {
		if (target == 0) {
			// need a new instance
			res.add(new ArrayList<Integer>(sol));
			return;
		}
		
		for (int i = start; i < num.length; i++) {
			if (num[i] > target) {
				break;
			} else {
				sol.add(num[i]);
				helper(num, i + 1, target - num[i], res, sol);
				sol.remove(sol.size() - 1);
				
				while (i < num.length - 1 && num[i] == num[i+1]) {
					i++;
				}
			}
		}
	}

}
